<?php

namespace App\Http\Controllers\App\V1;

use App\Enums\ActionEnum;
use App\Enums\RoomEnum;
use App\Http\Controllers\BaseController;
use App\Services\Accompany\AccompanyOrderService;
use App\Services\Tools\CurlService;
use App\Services\Tools\RedisService;
use Illuminate\Http\Request;            //引用http请求类
use App\Exceptions\BasicException;      //引入框架异常处理类
use App\Services\Tools\JwtService;      //引入jwt服务
use App\Services\Tools\FilterService;   //引入数美过滤服务
use Illuminate\Support\Facades\Config;  //引入配置类
use App\Response\Response;

class IndexController extends BaseController
{

    public function heartBeatCheck(Request $request)
    {
        //心跳检测,记录ip在线和用户在线,3分钟请求一次,过期时间200s
        //todo:定期清除过期的key值
        $token = $request->header('token', '');
        $uid = JwtService::getUid($token, false);

        $ip = $request->ip();

        $user_key = 'api_online:user';
        $ip_key = 'api_online:ip';

        $time = time() + 200;

        if (!empty($uid)) {
            app('redis')->zadd($user_key, $time, $uid);
        }

        //记录ip
        app('redis')->zadd($ip_key, $time, $ip);

        return Response::sendData(true);
    }

    public function bannerList(Request $request)
    {
        $token = $request->header('token', '');
        $uid = JwtService::getUid($token, true);

        $list = app('repo_index')->getBannerList($token);

        return Response::sendData($list);
    }

    public function getLisenceNav(Request $request)
    {
        $list = app('repo_index')->getLisenceNav();

        return Response::sendData($list);
    }

    public function getLisenceList(Request $request)
    {
        $list = app('repo_index')->getLisenceList();

        return Response::sendData($list);
    }

    public function getRecommendList(Request $request)
    {
        $list = app('repo_index')->getRecommendList();

        return Response::sendData($list);
    }

    public function getMoreList(Request $request)
    {
        $v = app('validator')->make(
            $request->all(),
            [
                'type'       => 'required|in:1,2,3,4',
                'lisence_id' => 'filled|numeric',
            ]
        );
        if ($v->fails()) {
            throw new BasicException(10010, getValidateMessage($v->messages()));
        }

        $type = $request->input('type', 1);
        $lisence_id = $request->input('lisence_id', 0);

        if (($type == 4) && empty($lisence_id)) {
            throw new BasicException(30035);
        }

        $list = app('repo_index')->getMoreList($type, $lisence_id);

        return Response::sendData($list);
    }

    public function getGeneralList(Request $request)
    {
        $v = app('validator')->make(
            $request->all(),
            [
                'lisence_id' => 'required|numeric',
                'page'       => 'filled|numeric',
            ]
        );
        if ($v->fails()) {
            throw new BasicException(10010, getValidateMessage($v->messages()));
        }
        //接收参数
        $param = $request->only(['lisence_id', 'online', 'tag_id', 'price', 'gender', 'type']);

        $perPage = 15;
        $page = $request->input('page', 1);

        $lisence_id = $request->input('lisence_id');

        $param['online'] = $request->input('online', 0);

        $param['gender'] = $request->input('gender', 0);

        $param['type'] = $request->input('type', 1);

        $list = app('repo_index')->getGeneralList($lisence_id, $param, $page, $perPage);

        return Response::sendList($list, $param);
    }

    public function getBlogTypeMessage($type): string
    {
        switch ($type){
            case 1:
                return '赞';
            case 2:
                return '回复';
            default:
                return '关注';
        }
    }

    public function orderMessage()
    {

        $blog_count = app('model_microblog_message')->where(['user_id' => UID, 'status' => 1])->count();
        $blog_detail = app('model_microblog_message')->where(['user_id' => UID, 'status' => 1])->orderBy('add_time',
            'desc')->with(['comment_user'])->first();
        $blog_message = '';
        if($blog_detail){
            $blog_detail_comment_user = $blog_detail->comment_user->nickname ?? '有人';
            $type = $this->getBlogTypeMessage($blog_detail->type);
            $blog_message = $blog_detail_comment_user . $type . '了你';
        }
        $userNewsCountData = app('model_user_news')->getUserNews(UID);

        $order = (new AccompanyOrderService())->getOrderMessage(UID);
        $data = [
            'lisence_count'     => 0,
            'lisence_last_time' => '',
            'demand_count'      => 0,
            'demand_last_time'  => '',
            'system_news'       => ['count' => $userNewsCountData['count'][1] ?? 0, "info" => $userNewsCountData['info']['system']],
            'notice_news'       => ['count' => $userNewsCountData['count'][2] ?? 0, "info" => $userNewsCountData['info']['notice']],
            'activity_news'       => ['count' => $userNewsCountData['count'][3] ?? 0, "info" => $userNewsCountData['info']['activity']],
            'order_news' => ['count' => $order['count'] ?? 0, "info" => $order['data'] ?: null],
            'blog_count'        => $blog_count,
            'blog_last_time'    => !empty($blog_detail) ? date('Y-m-d H:i:s', $blog_detail->add_time) : '',
            'blog_last_message' => $blog_message,
        ];

        return Response::sendData($data);
    }

    public function getIndexNav(Request $request)
    {
        $list = app('repo_index')->getIndexNav();

        return Response::sendData($list);
    }

    public function switch(Request $request)
    {
        $token = $request->header('token', '');
        $uid = JwtService::getUid($token, true);

        return Response::sendData([
            "new_player_task" => app('repo_new_player_task')->isActive($uid),
        ]);
    }

    public function getGameList(Request $request)
    {

        $env  = env('APP_ENV', 'dev') === 'dev' ? 'test' : 'online';
        $data = [
            [
                "game_name" => "五子棋",
                "link_url" => sprintf("http://game_platform.yutangwl.com/%s/wuziqi?hideNav=true", $env),
                "picture" => ""

            ],
            [
                "game_name" => "连连看",
                "link_url" => sprintf("http://game_platform.yutangwl.com/%s/lianliankan?hideNav=true", $env),
                "picture" => ""
            ]
        ];


        return Response::sendData($data);
    }

    public function getIndexAdvertisement(Request $request)
    {
        $index_json = app('redis')->get('nindex:advertisement');

        $arr = json_decode($index_json, true);

        if (!empty($arr) && is_array($arr)) {
            //随机取出一个广告
            $rand_ad = $arr[array_rand($arr, 1)];

            if ($rand_ad['type'] == 2) {
                //房间类型的广告检测是否上锁
                $room = app('model_user_room')->where('id', $rand_ad['content'])->first();
                if (empty($room) || !empty($room->password) || ($room->state != 1) || ($room->seal_time > time())) {
                    return Response::sendData(null);
                }else{
                    $rand_ad['room_type'] = RoomEnum::clientRoomType(RedisService::getRoomDetailByRoomId($rand_ad['content'],'sys_type_id'));
                }
            }

            return Response::sendData($rand_ad);
        }

        return Response::sendData(null);
    }

    public function reportDevice(Request $request)
    {
        $phone = $request->input('phone', '');
        $box_id = $request->input('box_id', '');
        $device_id = $request->header('deviceId', '');
        $channel_no = $request->header('CHANNELID', '');
//        $user_id = UID;
        $token = $request->header('token', '');
        $uid = JwtService::getUid($token, true);
        app('repo_user_device')->checkRegisterUser($uid, $device_id, $box_id, $phone);

        $is_report = get_sys_config('REPORT_DEVICE');
        //开启渠道监控的时候才做统计
        if (isset($is_report) && $is_report == 1) {
            //校验参数
            $v = app('validator')->make(
                $request->all(),
                [
                    'box_id' => 'required|min:1',
                ]
            );
            if ($v->fails()) {
                throw new BasicException(10010, getValidateMessage($v->messages()));
            }

//            //开启渠道监控的时候才做统计
            $token = $request->header('token', '');
            $uid = JwtService::getUid($token, true);

            if (!empty($channel_no) && ($channel_no != 'default')) {
                //监测是否存储过了
                $rn = app('model_channel_flux')->where('user_id', $uid)->first();

                if (!empty($rn)) {
                    throw new BasicException(10010);
                }

                $res = FilterService::checkUsers($device_id, $box_id, $channel_no);

                //有渠道标识和非默认渠道进行检测
                $data = [
                    'channel_no'  => $channel_no,
                    'user_id'     => $uid,
                    'add_time'    => time(),
                    'status'      => $res['status'],
                    'result'      => $res['result'],
                    'result_info' => $res['result_info'],
                    'request_id'  => $res['request_id'],
                    'device_id'   => $device_id,
                ];

                app('model_channel_flux')->create($data);
            }
        }

        return Response::sendData(true);
    }

    public function roomTypePlanet()
    {
        if (!isQipaoPlanet()) {
            throw new BasicException(10011);
        }
        $result = [
            [
                'id'   => '-2',
                'name' => '推荐',
                'type' => 1,
                'sort' => 6,
            ],
            [
                'id'   => '26',
                'name' => '电台',
                'type' => 1,
                'sort' => 4,
            ],
            [
                'id'   => '18',
                'name' => '女生',
                'type' => 1,
                'sort' => 12,
            ],
            [
                'id'   => '30',
                'name' => '男生',
                'type' => 1,
                'sort' => 10,
            ],
            [
                'id'   => '20',
                'name' => '娱乐',
                'type' => 1,
                'sort' => 6,
            ],
        ];

        return Response::sendData($result);
    }
}
